package com.phy.gsjl.dao;

import java.sql.Timestamp;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.phy.gsjl.entity.Message;
import com.phy.gsjl.entity.Page;
import com.phy.gsjl.form.QueryForm;

/**
 * message实体类的数据库访问层
 * 
 * @author curry
 *
 */
@Repository
public class MessageDAO {

	@Autowired
	private SessionFactory sessionFactory;

	// 获取日志对象
	private static Logger logger = Logger.getLogger(MessageDAO.class);

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 根据类型查询所有信息
	 * 
	 * @param type
	 * @return List<Message>
	 */
	@SuppressWarnings("unchecked")
	public List<Message> getAllMessages(Integer type) {
		String hql = "from Message where type = ?"; // 生成hql
		// 获取session，生成query对象，设置参数，执行查询操作
		List<Message> messages = this.getSession().createQuery(hql).setParameter(0, type).list();
		logger.info("==>In MessageDAO getAllMessages hql: " + hql);
		return messages;
	}

	/**
	 * 根据id查询对应信息
	 * 
	 * @param m_id
	 * @return Message
	 */
	public Message getMessageById(Integer m_id) {
		String hql = "from Message where m_id = ?";
		// 获取session，生成query对象，设置参数，执行查询操作
		Message message = (Message) this.getSession().createQuery(hql).setParameter(0, m_id).uniqueResult();
		logger.info("==>In MessageDAO getMessageById hql: " + hql);
		return message;
	}

	/**
	 * 根据内容模糊查询
	 * 
	 * @param indistinct
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Message> getMessageIndistinct(Integer type, String indistinct) {
		// hql，使用了%通配符
		String hql = "from Message where type = ? and m_details like '%" + indistinct + "%'";
		// 获取session，生成query对象，设置参数，执行查询操作
		List<Message> messages = this.getSession().createQuery(hql).setParameter(0, type).list();
		logger.info("==>In MessageDAO getMessageIndistinct hql: " + hql);
		return messages;
	}

	/**
	 * 根据内容和起始时间进行模糊查询
	 * 
	 * @param queryForm
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Message> getMessageByDetailsAndTime(QueryForm queryForm) {
		String indistinct = queryForm.getIndistinct(); // 模糊内容
		Timestamp beginTime = queryForm.getBeginTime(); // 开始时间
		Timestamp endTime = queryForm.getEndTime(); // 结束时间
		String hql = ""; // hql语句
		Query query = null; // 定义query对象
		if (indistinct != "" && indistinct != null) {
			// 内容和起始时间都不为空
			if (!beginTime.equals("") && beginTime != null) {
				hql = "from Message where type = ? and m_details like '%" + indistinct
						+ "%' and m_time between ? and ?";
				query = this.getSession().createQuery(hql);
				query.setParameter(0, queryForm.getType());
				query.setParameter(1, beginTime);
				query.setParameter(2, endTime);
			} else {
				// 只查询相关内容
				hql = "from Message where type = ? and m_details like '%" + indistinct + "%'";
				query = this.getSession().createQuery(hql);
				query.setParameter(0, queryForm.getType());
			}
		} else {
			// 只查询起始时间内的信息
			if (!beginTime.equals("") && beginTime != null) {
				hql = "from Message where type = ? and m_time between ? and ?";
				query = this.getSession().createQuery(hql);
				query.setParameter(0, queryForm.getType());
				query.setParameter(1, beginTime);
				query.setParameter(2, endTime);
			} else {
				hql = "from Message where type = ?";
				query = this.getSession().createQuery(hql);
				query.setParameter(0, queryForm.getType());
			}
		}
		// 执行查询操作
		List<Message> messages = query.list();
		logger.info("==>In MessageDAO getMessageByDetailsAndTime info of hql: " + hql);
		logger.info("==>In MessageDAO getMessageByDetailsAndTime info of QueryForm: " + queryForm.toString());
		return messages;
	}

	/**
	 * 添加信息
	 * 
	 * @param message
	 */
	public void addMessage(Message message) {
		logger.info("==>In MessageDAO addMessage message info: " + message.toString());
		this.getSession().save(message);
	}

	/**
	 * 根据ID更新信息状态
	 * 
	 * @param message
	 */
	public void updateMessageStatus(Message message) {
		logger.info("==>In MessageDAO updateMessageStatus message info: " + message.toString());
		this.getSession().update(message);
	}

	/**
	 * 返回不同类型序号最大的序号
	 * 
	 * @return
	 */
	public String getMessageMaxNum(Integer type) {
		String hql = "select max(m_number) from Message where type = ?";
		// 获取session，生成query对象，设置参数，执行查询操作
		String maxNumber = (String) this.getSession().createQuery(hql).setParameter(0, type).uniqueResult();
		logger.info("==>In MessageDAO getMessageMaxNum hql: " + hql);
		return maxNumber;
	}

	/**
	 * 获取总记录数
	 * 
	 * @return
	 */
	public Integer getTotalRecords(Integer type) {
		String hql = "select count(*) from Message where type = ?";
		// 获取session，生成query对象，设置参数，执行查询操作
		Query query = this.getSession().createQuery(hql).setParameter(0, type);
		Integer totalRecord = ((Long) query.iterate().next()).intValue();
		logger.info("==>In MessageDAO getTotalRecords hql: " + hql);
		return totalRecord;
	}

	/**
	 * 获取当页数据
	 * 
	 * @param currentPage
	 * @param totalRecord
	 * @return
	 */
	public List<Message> getCurrentPage(Integer currentPage, Integer totalRecord, Integer type) {
		Page page = new Page(totalRecord, 10, currentPage);
		String hql = "from Message where type = ?";
		Query query = this.getSession().createQuery(hql).setParameter(0, type);
		query.setFirstResult(page.getStartIndex()); // 设置开始查询的位置
		query.setMaxResults(page.getPageSize()); // 设置查询的条数
		List<Message> messages = query.list();
		return messages;
	}
}
